package com.example.compose

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import java.util.*

open class BaseComponentActivity: ComponentActivity() {


    @SuppressLint("SourceLockedOrientationActivity")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    }

    override fun attachBaseContext(newBase: Context?) {
        if(newBase==null) {
            super.attachBaseContext(newBase)
            return
        }
        val sp = newBase.getSharedPreferences("share_data", Context.MODE_PRIVATE)
        val language = sp.getString("language", Locale.getDefault().language)
        var locale: Locale = language?.let { Locale(it) }?:Locale.getDefault()
        if (language.equals("en", ignoreCase = true)) {
            locale = Locale.ENGLISH
        } else if (language.equals("ko", ignoreCase = true)) {
            locale = Locale.KOREA
        } else if (language.equals("zh", ignoreCase = true)) {
            locale = Locale.SIMPLIFIED_CHINESE
        } else if (language.equals("zh_TW", ignoreCase = true)) {
            locale = Locale.TRADITIONAL_CHINESE
        } else if (language.equals("ja", ignoreCase = true)) {
            locale = Locale.JAPAN
        } else if (language.equals("de", ignoreCase = true)) {
            locale = Locale.GERMANY
        } else if (language.equals("pt", ignoreCase = true)) {
            locale = Locale("pt")
        } else if (language.equals("es", ignoreCase = true)) {
            locale = Locale("es")
        } else if (language.equals("fr", ignoreCase = true)) {
            locale = Locale.FRENCH
        } else if (language.equals("ru", ignoreCase = true)) {
            locale = Locale("ru")
        } else if (language.equals("it", ignoreCase = true)) {
            locale = Locale.ITALY
        }
        Log.d("TAG", "changeAppLanguage: $language")
        val metrics = newBase.resources.displayMetrics
        val configuration = newBase.resources.configuration
        configuration.setLocale(locale)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            super.attachBaseContext(newBase.createConfigurationContext(configuration));
        } else {
            newBase.resources.updateConfiguration(configuration, metrics);
            super.attachBaseContext(newBase)
        }
    }
}